package com.mftour.common.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpResponse;
import org.apache.http.NoHttpResponseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.log4j.Logger;

/**
 * 
 * @author dell-pc
 * 
 * 
 */
public class HttpUtils {

	private final static Logger logger = Logger.getLogger(HttpUtils.class);

	/**
	 * 
	 * 连接服务器
	 * 
	 * @param url
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public static String getSeverDataGson(String url, String obj) {

		StringBuilder sb = new StringBuilder();

		HttpClient httpClient = new DefaultHttpClient();

		HttpPost httpPost = new HttpPost(url);

		logger.warn("httpUtil url=" + url);
		logger.warn("httpUtil obj=" + obj);
		try {
			httpPost.setEntity(new StringEntity(obj.toString(), HTTP.UTF_8));
		} catch (UnsupportedEncodingException e) {

			e.printStackTrace();
		}

		// Socket

		httpClient.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, 20000);
		// 网络超时20s

		httpClient.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 20000);

		HttpResponse httpResponse = null;
		int code = 0;
		try {
			httpResponse = httpClient.execute(httpPost);
			code = httpResponse.getStatusLine().getStatusCode();
		} catch (ClientProtocolException e) {

			e.printStackTrace();
		} catch (SocketTimeoutException e) {
			logger.warn("getSeverData 网络超时");
			return "";
		} catch (NoHttpResponseException e) {
			logger.warn("getSeverData URL地址错误");
			return "";
		} catch (IOException e) {
			e.printStackTrace();
		}

		if (code == 200) {

			InputStream instream = null;
			try {
				instream = httpResponse.getEntity().getContent();
			} catch (IllegalStateException e) {

				e.printStackTrace();
			} catch (IOException e) {

				e.printStackTrace();
			}

			BufferedReader reader = new BufferedReader(new InputStreamReader(

			instream));

			/*
			 * String line = null;
			 * 
			 * try { while ((line = reader.readLine()) != null) {
			 * Log.w("httpUtil", "line=" + line); sb.append(line);
			 * 
			 * } } catch (IOException e) {
			 * 
			 * e.printStackTrace(); }
			 */

			char[] tempchars = new char[1024];
			int charread = 0;
			try {
				while ((charread = reader.read(tempchars)) != -1) {
					// 同样屏蔽掉\r不显示
					if ((charread == tempchars.length) && (tempchars[tempchars.length - 1] != '\r')) {
						sb.append(tempchars);
					} else {
						for (int i = 0; i < charread; i++) {
							if (tempchars[i] == '\r') {
								continue;
							} else {
								sb.append(tempchars[i]);
							}
						}
					}
				}
			} catch (IOException e) {

			}

			logger.warn("httpUtil result=" + sb.toString());
			return sb.toString();

		}

		return "";
	}

	/**
	 * 获取用户真实ip
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
			System.out.println("Proxy-Client-IP:"+ip);
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
			System.out.println("WL-Proxy-Client-IP:"+ip);
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
			System.out.println("RemoteAddr:"+ip);
		}
		return ip;
	}
}
